package com.dcy.znoa.common.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.APIConnectionException;
import cn.jpush.api.common.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Message.Builder;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
/**
 * 极光推送帮助类
 * Created by pengyu on 2017/10/6.
 */
public class JpushUtils {

    /** 日志信息 */
    private static final Logger LOG = Logger.getLogger("[推送帮助类]:");

    /** jpush_app_key */
    public static final String jpush_app_key = "da8e2f21e312a6fdafce06e2";//dcy:d96c923574dd48a3a97d7fd2  dz:2d76bc7d25e12643a81588e0

    /** jpush_master_secret */
    public static final String jpush_master_secret = "fdc1fce002795a3179d49870";//dcy:2772e13ff59ff3d2c96b5ff0 dz:d244597db2914f0bf1da2fd7

    /**
     * 推送
     * @param regId 表示用户的 push_id  action 表示 message  ；
     *              pushMap中 action对应的值为 PushBusinessCode的code
     *              data 表示JSON.toJSONString(pushData) json格式的字符串
     *              com.alibaba.fastjson.JSON
     */
    public static void pushMsgByRegId(String regId, Map<String, String> pushMap) {

        JPushClient jpushClient = new JPushClient(jpush_master_secret, jpush_app_key, 20);

        Builder builder = Message.newBuilder();
        builder.setMsgContent("");

        if (pushMap != null) {
//            for (String key : pushMap.keySet()) {
//                String value = pushMap.get(key);
//                builder.addExtra(key, value);
//            }
            for(Map.Entry entry : pushMap.entrySet()){
                builder.addExtra(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
            }
        }
        long time = Math.round(System.currentTimeMillis()/1000.0)+(2*60);// 有效时间为两分钟
        builder.addExtra("timeout", time);
        try {
            PushResult result = jpushClient.sendPush(
                    PushPayload.newBuilder()
                            .setPlatform(Platform.all())
                            .setAudience(Audience.registrationId(regId))
                            .setOptions(Options.newBuilder()
                                    .setApnsProduction(false).build())
                            .setMessage(builder.build())
                            .build());

            LOG.info("推送成功 - " + result);
        } catch (APIConnectionException e) {
            LOG.error("连接错误,请稍后重试.", e);
        } catch (APIRequestException e) {
            e.printStackTrace();
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }
    public static void main1(String[] args) {
        System.out.println(Math.round(System.currentTimeMillis()/1000.0)+2*60);
        System.out.println(System.currentTimeMillis());
    }
    public static void main(String[]	 args) throws IllegalArgumentException, IllegalAccessException {

//        try {
//            Map<String, String> pushData = ReflectUtils.objectParseMap(reservationDto);
//            Map<String, String> pushMap = new HashMap<String, String>();
//            pushMap.put("action", PushBusinessCode.RESERVATION.getCode());
//            pushMap.put("data", JSON.toJSONString(pushData));
//            // 在此调用获取渠道还是app ,通过userID pengyu add 同一个手机号码通过不同渠道对应的UERID不同
//            boolean isScoket = WebSocketUtils.hasConnection(userId);
//            if (isScoket) {
//                LOG.info("websocket--------预约推送给此用户userid 【" + userInfo.getUser_id() + "】");
//                WebSocketUtils.sendMessage(userId, JSON.toJSONString(pushMap));
//            } else {
//                LOG.info("极光---------预约推送给此用户 【" + userInfo.getJpush_id() + "】");
//                if (StringUtils.isNotBlank(userInfo.getJpush_id()))
//                    JpushUtils.pushMsgByRegId(userInfo.getJpush_id(), message, pushMap);
//            }


//        ChargeDto dto = new ChargeDto();
//        dto.setActionType("1");
//        dto.setChargerId("123");
//        dto.setChargeSn("321");
//        dto.setPlugNo("1");
//        LOG.info("1 " + 1);
//        LOG.error(2);
//        LOG.debug(DateUtil.getDate());
//        LOG.debug(3);
//        LOG.warn("4");
//        Map<String, String> pushData = ReflectUtils.objectParseMap(dto);
//        Map<String, String> pushMap = new HashMap<String, String>();
//        pushMap.put("action", PushBusinessCode.CHARGE.getCode());
//        pushMap.put("data", JSON.toJSONString(pushData));
//        System.out.println(JSON.toJSONString(pushMap));
//        // 08027d2100f  18071adc030d728d2f6
//        JpushUtils.pushMsgByRegId("080a604889c", "您在通威国际中心的1号桩已开始充电", pushMap);
    }

}
